package ee.maoinvest.backend.model.dao.postgresqlimplementations;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import ee.maoinvest.backend.database.ConnectionManager;
import ee.maoinvest.backend.model.dao.RegularReadingOfParentElectricityMeterDAO;
import ee.maoinvest.backend.model.data.RegularReadingOfParentElectricityMeter;

public class RegularReadingOfParentElectricityMeterDAOPostgresqlImpl implements RegularReadingOfParentElectricityMeterDAO
{

	Logger logger = Logger.getLogger(RegularReadingOfParentElectricityMeterDAOPostgresqlImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	private final int WARNING_NO_ROWS_AFFECTED = 0;
	private int rowsAffected;
	
	public RegularReadingOfParentElectricityMeterDAOPostgresqlImpl(Connection dbConnection)
	{
		this.dbConnection = dbConnection;
	}
	
//-----------------START OF BASIC CRUD-----------------------------------
	@Override
	public int insertRegularReadingOfParentElectricityMeter(
			RegularReadingOfParentElectricityMeter regularReadingOfParentElectricityMeter) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "INSERT INTO Regular_readings_of_parent_electricity_meter " + 
				"(parentElectricityMeterFK, dateParentElectricityMeterReadingWasTaken, " +  
				"parentElectricityMeterDaytimeReading, parentElectricityMeterNightTimeReading, parentElectricityMeterReactivePowerReading) " + 
				"VALUES " + 
				"(?, ?, " + 
				"?, ?, ?);";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			
			preparedStatement.setInt		(1, regularReadingOfParentElectricityMeter.getParentElectricityMeterFK());
			preparedStatement.setDate		(2, regularReadingOfParentElectricityMeter.getDateParentElectricityMeterReadingWasTaken());
			preparedStatement.setBigDecimal	(3, regularReadingOfParentElectricityMeter.getParentElectricityMeterDaytimeReading());
			preparedStatement.setBigDecimal	(4, regularReadingOfParentElectricityMeter.getParentElectricityMeterNightTimeReading());
			preparedStatement.setObject		(5, regularReadingOfParentElectricityMeter.getParentElectricityMeterReactivePowerReading(), Types.NUMERIC);
			
			logger.info(preparedStatement.toString());
			rowsAffected = preparedStatement.executeUpdate();
			
			if (rowsAffected == 1)
			{
				resultSet = preparedStatement.getGeneratedKeys();
				resultSet.next(); //answer consist only 1 row, so move the cursor just once to start to process the result
				int newId = resultSet.getInt(1); // 1, because identifiers are held in the first column 
				regularReadingOfParentElectricityMeter.setRegularReadingOfParentElectricityMeterID(newId);
				return rowsAffected;
			}
			else
			{
				System.out.println("No rows affected!");
				logger.info("Unsuccessful insertion to a database: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (Exception e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public RegularReadingOfParentElectricityMeter getRegularReadingOfParentElectricityMeterByID(
			int regularReadingOfParentElectricityMeterID) 
	{
		resultSet = null;
		RegularReadingOfParentElectricityMeter regularReadingOfParentElectricityMeterRetrieved = null;
		sql = "SELECT * FROM Regular_readings_of_parent_electricity_meter WHERE regularReadingOfParentElectricityMeterID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
						sql,
						ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_READ_ONLY
					);
			//filling the placeholders 
			preparedStatement.setInt(1, regularReadingOfParentElectricityMeterID);
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of a received data set (so it can start to read and process data)
			resultSet.beforeFirst();
			
			if (resultSet.next())
			{
				regularReadingOfParentElectricityMeterRetrieved = new RegularReadingOfParentElectricityMeter();
				regularReadingOfParentElectricityMeterRetrieved.setRegularReadingOfParentElectricityMeterID(resultSet.getInt("regularReadingOfParentElectricityMeterID"));
				regularReadingOfParentElectricityMeterRetrieved.setParentElectricityMeterFK(resultSet.getInt("parentElectricityMeterFK"));
				regularReadingOfParentElectricityMeterRetrieved.setDateParentElectricityMeterReadingWasTaken(resultSet.getDate("dateParentElectricityMeterReadingWasTaken"));
				regularReadingOfParentElectricityMeterRetrieved.setParentElectricityMeterDaytimeReading(resultSet.getBigDecimal("parentElectricityMeterDaytimeReading"));
				regularReadingOfParentElectricityMeterRetrieved.setParentElectricityMeterNightTimeReading(resultSet.getBigDecimal("parentElectricityMeterNightTimeReading"));
				regularReadingOfParentElectricityMeterRetrieved.setParentElectricityMeterReactivePowerReading((BigDecimal) resultSet.getObject("parentElectricityMeterReactivePowerReading"));
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return regularReadingOfParentElectricityMeterRetrieved;
	}

	@Override
	public int updateRegularReadingOfParentElectricityMeter(
			RegularReadingOfParentElectricityMeter regularReadingOfParentElectricityMeter) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "UPDATE Regular_readings_of_parent_electricity_meter " + 
				"SET parentElectricityMeterFK = ?, dateParentElectricityMeterReadingWasTaken = ?, " +  
				"parentElectricityMeterDaytimeReading = ?, parentElectricityMeterNightTimeReading = ?, parentElectricityMeterReactivePowerReading = ? " + 
				"WHERE regularReadingOfParentElectricityMeterID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			
			preparedStatement.setInt		(1, regularReadingOfParentElectricityMeter.getParentElectricityMeterFK());
			preparedStatement.setDate		(2, regularReadingOfParentElectricityMeter.getDateParentElectricityMeterReadingWasTaken());
			preparedStatement.setBigDecimal	(3, regularReadingOfParentElectricityMeter.getParentElectricityMeterDaytimeReading());
			preparedStatement.setBigDecimal	(4, regularReadingOfParentElectricityMeter.getParentElectricityMeterNightTimeReading());
			preparedStatement.setObject		(5, regularReadingOfParentElectricityMeter.getParentElectricityMeterReactivePowerReading(), Types.NUMERIC);
			preparedStatement.setObject		(6, regularReadingOfParentElectricityMeter.getRegularReadingOfParentElectricityMeterID(), Types.NUMERIC);
			
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Update sucessful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.error("Update was unsuccesful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
			return WARNING_NO_ROWS_AFFECTED;		
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}

	@Override
	public int deleteRegularReadingOfParentElectricityMeter(
			int regularReadingOfParentElectricityMeterID) 
	{
		resultSet = null;
		rowsAffected = WARNING_NO_ROWS_AFFECTED;
		sql = "DELETE FROM Regular_readings_of_parent_electricity_meter WHERE regularReadingOfParentElectricityMeterID = ?;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(sql);
			preparedStatement.setInt(1, regularReadingOfParentElectricityMeterID);
			rowsAffected = preparedStatement.executeUpdate();
			
			
			if (rowsAffected == 1)
			{
				logger.info("Deletion successful: " + preparedStatement.toString());
				return rowsAffected;
			}
			else
			{
				logger.info("Deletion unsuccessful: " + preparedStatement.toString());
				return WARNING_NO_ROWS_AFFECTED;
			}
		}
		catch(SQLException e) 
		{
			e.printStackTrace();
			return WARNING_NO_ROWS_AFFECTED;
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
	}
//-----------------END OF BASIC CRUD-----------------------------------	

	@Override
	public List<RegularReadingOfParentElectricityMeter> getAllRegularReadingsOfParentElectricityMeters() 
	{
		List<RegularReadingOfParentElectricityMeter> listOfRegularReadingsOfParentElectricityMeters = 
				new ArrayList<RegularReadingOfParentElectricityMeter>();
		RegularReadingOfParentElectricityMeter regularReadingOfParentElectricityMeterRetrieved = null;
		sql = "SELECT * FROM Regular_readings_of_parent_electricity_meter;";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
					sql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY
				);
			
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of the result set. Otherwise it can not start reading the result set. 
			resultSet.beforeFirst();
			
			while (resultSet.next())
			{	
				regularReadingOfParentElectricityMeterRetrieved = new RegularReadingOfParentElectricityMeter();
				regularReadingOfParentElectricityMeterRetrieved.setRegularReadingOfParentElectricityMeterID(resultSet.getInt("regularReadingOfParentElectricityMeterID"));
				regularReadingOfParentElectricityMeterRetrieved.setParentElectricityMeterFK(resultSet.getInt("parentElectricityMeterFK"));
				regularReadingOfParentElectricityMeterRetrieved.setDateParentElectricityMeterReadingWasTaken(resultSet.getDate("dateParentElectricityMeterReadingWasTaken"));
				regularReadingOfParentElectricityMeterRetrieved.setParentElectricityMeterDaytimeReading(resultSet.getBigDecimal("parentElectricityMeterDaytimeReading"));
				regularReadingOfParentElectricityMeterRetrieved.setParentElectricityMeterNightTimeReading(resultSet.getBigDecimal("parentElectricityMeterNightTimeReading"));
				regularReadingOfParentElectricityMeterRetrieved.setParentElectricityMeterReactivePowerReading((BigDecimal) resultSet.getObject("parentElectricityMeterReactivePowerReading"));
		
				listOfRegularReadingsOfParentElectricityMeters.add(regularReadingOfParentElectricityMeterRetrieved);
			}
		} 
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return listOfRegularReadingsOfParentElectricityMeters;
	}
	
}
